package com.example.mytestdemo.scale.zoom.draw;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;


import java.util.ArrayList;
import java.util.List;

public class DrawPrviewView extends View {

    public static int type = 1;

    public static int MAX_HEIGHT = 4000;

    Path mPath;
    Canvas mCanvas;
    Paint mPaint;

    Paint mEraserPaint=new Paint();
    int width;
    int height;

    float mX = 0.0f;
    float mY = 0.0f;

    private Bitmap cachebBitmap;

    private boolean canPaint = true; //能否绘制
    private int paintColor = Color.RED;
    private boolean isOpenMultiFingered;
//    private MultiFingeredPaintService service;
    public DrawPrviewView(Context context) {
        super(context);
//        service = ARouter.getInstance().navigation(MultiFingeredPaintService.class);
    }

    public DrawPrviewView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
//        service = ARouter.getInstance().navigation(MultiFingeredPaintService.class);
    }

    public DrawPrviewView(Context context, AttributeSet attrs) {
        super(context, attrs);
//        service = ARouter.getInstance().navigation(MultiFingeredPaintService.class);
//        isOpenMultiFingered = service.isOpenMultiFingered()
    }

    private boolean isOne = true;
    private int penMode = 1;//1:画笔；2：橡皮擦
    private List<Integer[]> mRequestPath;
    private DrawPrviewData mRequestData;

    public synchronized void init(int wid, int hei, int paintColor) {
        this.paintColor = paintColor;
        if (wid == 0 || hei == 0)
            return;
        //mAndroidMsgProxy = AndroidMsgProxy.getInstance(LekeTeacherApplicationLike.getLekeApplication());
        mRequestPath = new ArrayList<Integer[]>();

        penMode = 1;
        width = wid;
        height = hei <= MAX_HEIGHT ? hei : MAX_HEIGHT;

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(paintColor);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(2);
        Log.i("DrawPrviewView", "------" + width + "---" + height + "DrawPrviewView");
        try {
            Config config = Config.ARGB_8888;
            cachebBitmap = Bitmap.createBitmap(width, height, config);
        } catch (OutOfMemoryError e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        if (cachebBitmap != null) {
            mCanvas = new Canvas(cachebBitmap);
        }

        //cachebBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Log.i("DrawPrviewView", "------" + width + "---" + height);
        //mCanvas = new Canvas(cachebBitmap);
        mPath = new Path();

		/*
        PrviewListener.getInstence().doCallBack(new onPrviewListener() {

			@Override
			public void onPrviewData(ArrayList<DrawPrviewData> drawApp) {
				// TODO Auto-generated method stub
				curSolvDrawApp = drawApp;
				starPrview(fa);
			}
		});
		*/

    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        //canvas.drawColor(Color.WHITE);
        if (null != cachebBitmap) {
            canvas.drawBitmap(cachebBitmap, 0, 0, null);
            mPaint.setColor(paintColor);
            canvas.drawPath(mPath, mPaint);
        }

        if (penMode == 2 && isMove) {
            //设置画笔的颜色
            mEraserPaint.setColor(paintColor);
            //绘制一个小圆（作为小球）
            canvas.drawCircle(mX, mY, 40, mEraserPaint);
        }
    }

    private boolean isMove = false;


    public void clear() {
        if (null != mCanvas) {
            Paint mPaint = new Paint();
            mPaint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR));
            mCanvas.drawPaint(mPaint);
            mPaint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.SRC));
            invalidate();
        }
    }

    //画线条
    public void penFun() {
        if (null != mPaint)
            mPaint.reset();
        else
            mPaint = new Paint();
        isMove = false;

        mPaint.setAntiAlias(true);
        mPaint.setColor(paintColor);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(2);
        penMode = 1;
    }

    //橡皮擦功能
    public void eraserFun() {

        if (null != mPaint)
            mPaint.reset();
        else
            mPaint = new Paint();
        mPaint.setColor(Color.TRANSPARENT);
        mPaint.setAntiAlias(false);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(40);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setAlpha(0xFF);
        mPaint.setColor(Color.BLUE);
        //mPaint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_IN));
        mPaint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR));
        penMode = 2;

    }

    private void eraserFun(int width) {
        if (null != mPaint)
            mPaint.reset();
        else
            mPaint = new Paint();
        mPaint.setColor(Color.TRANSPARENT);
        mPaint.setAntiAlias(false);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(width);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setAlpha(0xFF);
        mPaint.setColor(Color.BLUE);
        //mPaint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_IN));
        mPaint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.CLEAR));
        penMode = 2;
    }

    public boolean isClickEraser = false;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (canPaint) {
            if(isOpenMultiFingered){
                if (event.getPointerCount() > 1) {
                    this.getParent().requestDisallowInterceptTouchEvent(false);
                    return false;
                } else {
                    return doDraw(event);
                }
            }else if(event.getToolType(0) != MotionEvent.TOOL_TYPE_FINGER){
                return doDraw(event);
            }

        }
        this.getParent().requestDisallowInterceptTouchEvent(false);
        return false;

    }
    private boolean doDraw(MotionEvent event){
        this.getParent().requestDisallowInterceptTouchEvent(true);
        int act = event.getAction();
        float x = event.getX();
        float y = event.getY();
        switch (act) {
            case MotionEvent.ACTION_DOWN:

                if (!isClickEraser) {
                    penFun();
                } else {
                    eraserFun();
                }
                isMove = false;
                mPath.moveTo(x, y);
                mRequestPath.clear();
                break;
            case MotionEvent.ACTION_MOVE:
                isMove = true;
                if (penMode == 1) {
                    mPath.quadTo(mX, mY, x, y);
                } else if (penMode == 2 && mCanvas != null) {
                    mCanvas.drawLine(mX, mY, x, y, mPaint);
                    mCanvas.drawCircle(x, y, 12, mPaint);

                }
                break;
            case MotionEvent.ACTION_UP:
                if (null != mCanvas) {
                    mCanvas.drawPath(mPath, mPaint);
                }

                mPath.reset();
                isMove = false;

                doRequest();
                break;
        }
        Integer[] actionPostion = {(int) event.getX(), (int) event.getY()};
        mRequestPath.add(actionPostion);
        invalidate();
        mX = x;
        mY = y;

        return true;
    }

//    /**
//     * 判断是否是乐课平板
//     */
//    private boolean isLekeSupportMode(@NonNull MotionEvent event) {
//        IStudentRomConfigMainService navigation = ARouter.getInstance().navigation(IStudentRomConfigMainService.class);
//        if (navigation != null) {
//            return navigation.isHandleBrushTouchEvent(event);
//        }
//        return false;
//    }

    private void doRequest() {
        Integer[][] point = new Integer[mRequestPath.size()][2];
        //这里做缩放
        //float scaleX = (float) PC_WITH / (float) mBitmap.getWidth();
        //float scaleY = (float) PC_HEIGHT / (float) mBitmap.getHeight();
        //我这是做一个参数， 长是 1000，宽是500，等比做法，根据自身的长和宽，保存对比值
        for (int i = 0; i < point.length; i++) {
            point[i] = mRequestPath.get(i);
            if (point[i] != null) {
                point[i][0] = (int) ((float) point[i][0] / width * 1000);//(int) (point[i][0] * scaleX);
                point[i][1] = (int) ((float) point[i][1] / height * 1000);//(int) (point[i][1] * scaleY);
            }
        }
        mRequestData = new DrawPrviewData();
        mRequestData.setP(point);
        mRequestData.setColor(paintColor);
        mRequestData.setQuestionId(questionId);
        if (2 == penMode)
            mRequestData.setR(true);
        else
            mRequestData.setR(false);

        if (mActionUpListener != null) {
            mActionUpListener.onActionUp(mRequestData);
        }
        mRequestPath.clear();
    }


    public synchronized void drawByData(DrawPrviewData drawPrviewData) {
        mRequestData = drawPrviewData;
        if (drawPrviewData == null || drawPrviewData.getP() == null) {
            return;
        }
        Path path = getPath(drawPrviewData.getP());

        if (drawPrviewData.isR()) //橡皮擦
        {
            eraserFun(30);
        } else {
            penFun();
            mPaint.setColor(paintColor);
        }
        if (mCanvas == null) {
            try {
                Config config = Config.ARGB_4444;
                cachebBitmap = Bitmap.createBitmap(width, height, config);
                if (cachebBitmap != null) {
                    mCanvas = new Canvas(cachebBitmap);
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                Log.e("DrawPrviewView","drawByData  exception "+e.getMessage());
            }
        }
        if(mCanvas!=null) {
            mCanvas.drawPath(path, mPaint);
        }
        invalidate();
    }

    public synchronized void drawViewByData(final List<DrawPrviewData> drawDataList) {

        if (drawDataList != null && width > 0 && height > 0) {
            for (DrawPrviewData drawPrviewData : drawDataList) {
                if (drawPrviewData != null) {
                    Path path = getPath(drawPrviewData.getP());
                    if (drawPrviewData.isR()) //橡皮擦
                    {
                        eraserFun(30);
                    } else {
                        penFun();
                        mPaint.setColor(paintColor);
                    }
                    if (mCanvas == null) {
                        try {
                            Config config = Config.ARGB_4444;
                            cachebBitmap = Bitmap.createBitmap(width, height, config);
                            mCanvas = new Canvas(cachebBitmap);
                        }catch (OutOfMemoryError e){
                            e.printStackTrace();
                            Log.e("DrawPrviewView","drawViewByData  exception "+e.getMessage());
                        }
                    }
                    if(mCanvas!=null) {
                        mCanvas.drawPath(path, mPaint);
                    }
                }
            }
        }
        invalidate();

    }


    private Path getPath(Integer[][] drawPath) {
        Path path = new Path();
        if (drawPath != null) {
            if (drawPath.length > 0) {
                for (int i = 0; i < drawPath.length; i++) {
                    int paintX = drawPath[i][0] * width / 1000;
                    int paintY = drawPath[i][1] * height / 1000;
                    if (i == 0) {
                        path.moveTo(paintX, paintY);
                    } else {
                        path.lineTo(paintX, paintY);
                    }
                }
            }
        }
        return path;
    }

    private ActionUpListener mActionUpListener; //抬手动作监听

    /**
     * 描述:监听手指抬起事件
     */
    public interface ActionUpListener {

        void onActionUp(DrawPrviewData data);

    }

    public void setActionUpListener(ActionUpListener mActionUpListener) {
        this.mActionUpListener = mActionUpListener;
    }

    private long questionId;

    public void setQuestionId(long questionId) {
        this.questionId = questionId;
    }


    //垃圾回收
    public void reclecyBitmap() {
        if (cachebBitmap != null && !cachebBitmap.isRecycled()) {
            cachebBitmap.recycle();
            cachebBitmap = null;
        }

        if (mPath != null) {
            mPath = null;
        }
        if (mPaint != null) {
            mPaint = null;
        }
        if (mCanvas != null) {
            mCanvas = null;
        }

        System.gc();
    }

    public DrawPrviewData getmRequestData() {
        return mRequestData;
    }

    public void setmRequestData(DrawPrviewData mRequestData) {
        this.mRequestData = mRequestData;
    }

    public void setCanPaint(boolean canPaint) {
        this.canPaint = canPaint;

    }
}
